import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/Login.vue')
    },

    {
      path: '/repair',
      name: 'repair',
      component: () => import('../views/Layout.vue'),
      children: [
        {
          path: '',
          component: () => import('../views/Repair.vue')
        }
      ]
    },

    {
      path: '/user',
      name: 'user',
      component: () => import('../views/Layout.vue'),
      children: [
        {
          path: '',
          component: () => import('../views/User.vue')
        }
      ]
    },

    {
      path: '/worker',
      name: 'worker',
      component: () => import('../views/Layout.vue'),
      children: [
        {
          path: '',
          component: () => import('../views/Worker.vue')
        }
      ]
    },

    {
      path: '/user-advice',
      name: 'user-advice',
      component: () => import('../views/Layout.vue'),
      children: [
        {
          path: '',
          component: () => import('../views/UserAdvice.vue')
        }
      ]
    },

    {
      path: '/worker-advice',
      name: 'worker-advice',
      component: () => import('../views/Layout.vue'),
      children: [
        {
          path: '',
          component: () => import('../views/WorkerAdvice.vue')
        }
      ]
    }
  ],
})

router.beforeEach((to) => {
  const userInfo = localStorage.getItem('userInfo');
  const isLoginPage = to.path === '/login';

  // 已登录，访问登录页，重定向到首页
  if (isLoginPage && userInfo) {
    return '/repair';
  }

  // 非登录页，并且没有登录态，重定向到登录页
  if (!isLoginPage && !userInfo) {
    return '/login';
  }

  return true;
})

export default router
